import { observable, action } from 'mobx-miniprogram'
import { _getStorage, _setStorage } from '../utils/util'

export const store = observable({

  // 数据字段
  shopList: [],
  checked: false,
  login: false,

  // 计算属性
  get count() {
    return this.shopList.reduce((value, item) => {
      return value += item.num
    }, 0)
  },

  // 计算总价
  get totalPrice () {
    return this.shopList.reduce((value, item) => {
      return value += item.checked ? item.num * item.price : 0
    }, 0)
  },

  get checkedAll() {
    return this.shopList.every((item) => {
      return item.checked
    })
  },

  // actions  删除商品
  delete: action(function (id) {
    let res = this.shopList.reduce((value, item) => {
      return item.spuId == id ? value : [...value, item]
    }, [])
    this.shopList = res
    this.setData()
  }),

  // 加入购物车
  add: action(function(obj) {
    let bool
    let list = this.shopList.reduce((value, item) => {
      if(item.spuId === obj.spuId) {
        item.num += 1
        bool = true
      }
      return [...value, item]
    }, [])
    
    this.shopList = bool ? [...list] : [obj, ...this.shopList]
    this.setData()
  }),

  // 选择单个
  select: action(function(id) {
    this.shopList = this.shopList.reduce((value, item) => {
      if(item.spuId === id) {
        item.checked = !item.checked 
      }
      return [...value, item]
    }, [])
    this.setData()
  }),

  // 修改全选
  changeCheckedAll: action(function(checked) {
    this.shopList = this.shopList.reduce((value, item) => {
      item.checked = checked
      return [...value, item]
    }, [])
    this.setData()
  }),

  // 修改数量
  changeShopNum: action(function(id, num) {
    this.shopList = this.shopList.reduce((value, item) => {
      if(item.spuId === id) item.num = num
      return [...value, item]
    }, [])
    this.setData()
  }),

  loadData: action(async function() {
    await this.getUser()
    let data = await _getStorage(this.login)
    if(data === 'undefined') {
      this.setData()
      data = []
    }
    this.shopList = data
  }),

  setData: action(function() {
    _setStorage(this.login, this.shopList)
  }),

  // 获取用户信息
  getUser: action(async function() {
    let res = await _getStorage('user')
    this.login = res ? res.nickName : false
  })

})